package com.wl.bbs.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wl.bbs.entity.Result;
import com.wl.bbs.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        if (session.getAttribute("myinfo") == null) {
                                                             //ajax 请求
            if(request.getHeader("Accept").startsWith("application/json")){
                Result result = new Result(0,"未登录",null);
                String json = new ObjectMapper().writeValueAsString(result);
                response.getWriter().append(json);
            }else {
                session.setAttribute("getRequestURI",request.getRequestURI());
                // TODO  打开页面时，提示用户必须先登录 cause=1 表示未登录
                String contextPath = request.getServletContext().getContextPath();
                response.sendRedirect(contextPath+"login.html?cause=1");
            }

            //        这必须是管理员才能进
            if(request.getServletPath().startsWith("/back")){
                User myinfo = (User) session.getAttribute("myinfo");
                if ("admin".equals(myinfo.getRole())==false) {
                    if (request.getHeader("Accept").startsWith("application/json")) {}
                        Result result = new Result(0,"权限不足",null);
                        String json = new ObjectMapper().writeValueAsString(result);
                        response.getWriter().append(json);
                }else {
                    session.setAttribute("getRequestURI",request.getRequestURI());
                    // TODO  打开页面时，提示用户必须先登录 cause=2 表示权限不足
                    String contextPath = request.getServletContext().getContextPath();
                    response.sendRedirect(contextPath+"login.html?cause=2");
                }
            }
            return false;
        }
        return true;
    }
}
